import React from 'react';
import {withRouter} from 'react-router-dom';
import {Menu, Icon} from 'antd';
import routes from '../../common/Routes';
const SubMenu = Menu.SubMenu;


@withRouter
export default class MenuNow extends React.Component {
  // @observable currentKey = [routes[0].children[0].path];
  state = {
    openKeys: [routes[0].key],
    currentKey:[routes[0].children[0].path]
  }
  componentWillReceiveProps (nextProps) {
    const {pathname} = nextProps.location;
    const currentKey = [pathname || routes[0].children[0].path];
    // console.log(this.currentKey[0]);
    const currentSub = routes.find((v) => {
      if (v.children && v.children.length) {
        return v.children.find((value) => value.path === currentKey[0])
      }
      return false;
    });
    if (currentSub && currentSub.key) {
      this.setState({ 
        currentKey,
        openKeys:[currentSub.key]
      });
    } else {
      this.setState({ 
        currentKey: [],
        openKeys:[]
      });
    }
    
  }
  componentDidMount(){

  }
  resizeFn = () => {
    
  }
  selectMenu = ({item, key, selectedKeys}) => {
    const {history} = this.props;
    history.push (selectedKeys[0]);
  };
  openSubMenu = (item) => {
    this.setState({ 
      openKeys:[item[item.length -1]] 
    });
  }
  render () {
    // console.log('渲染一次');
    return (
      <Menu
        theme="dark"
        defaultSelectedKeys={[routes[0].path]}
        selectedKeys={this.state.currentKey}
        openKeys={this.state.openKeys}
        mode="inline"
        onSelect={this.selectMenu}
        onOpenChange={this.openSubMenu}
      >
        {routes.map ((v, index) => {
          if (v.isNotMenu) {
            return null;
          }
          return (
            <SubMenu key={v.key} title={<span><Icon type={v.icon} style={{fontSize: 18}} /><span>{v.name}</span></span>}>
            {
              v.children.map((inV,inIndex) => {
                return (
                  <Menu.Item key={inV.path}>
                    <Icon type={inV.icon || 'home'} style={{fontSize: 18}} />
                    <span>{inV.name}</span>
                  </Menu.Item>
                );
              })
            }
            </SubMenu>
          )
        })}
      </Menu>
    );
  }
}
